﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Lidgren.Network;
using Model.LiveControl;
using Network;
using Network.Messages.FileTranser;

namespace Providers.FileTransfer.Server
{
    public class FileTransferServerProvider : Provider
    {
        private readonly StreamingServer[] _clients = new StreamingServer[8];
        private readonly Queue _fileQueue = new Queue();
        private uint _number;

        public FileTransferServerProvider(NetworkPeer network) : base(network)
        {
        }

        public static int Channel { get; } = 1;

        public override void RegisterMessageHandlers()
        {
            Network.RegisterMessageHandler<RequsetCopyFileMessage>(OnRequsetCopyFileMessageRecived);
        }

        public override void Heartbeat(float now, uint frameCounter)
        {
            for (var i = 0; i < _clients.Length; i++)
            {
                var client = _clients[i];
                if (client == null || client.FlagComplete)
                {
                    if (_fileQueue.Count == 0)
                        continue;
                    client = (StreamingServer)_fileQueue.Dequeue();
                }
                for (var j = 0; j < 50; j++)
                {
                    client.Heartbeat();
                    if (client.FlagComplete)
                    {
                        break;
                    }
                }
            }
        }

        private void OnRequsetCopyFileMessageRecived(MessageEventArgs<RequsetCopyFileMessage> obj)
        {
            var parentDir = obj.Message.DirPath + "\\";
            foreach (var file in obj.Message.FileList)
            {
                CreateFileCopyTask(file, parentDir, obj.Connection);
            }
            foreach (var dir in obj.Message.DirList)
            {
                var tInfo = new DirectoryInfo(dir);
                YiedDirectory(obj.Connection, tInfo, parentDir + tInfo.Name + "\\");
            }
        }

        private void YiedDirectory(NetConnection connection, DirectoryInfo tInfo, string parentDir)
        {
            foreach (var directoryInfo in tInfo.GetDirectories())
            {
                // 发送新建文件夹消息

                //self
                YiedDirectory(connection, directoryInfo, parentDir + directoryInfo.Name + "\\");
            }
            foreach (var fileInfo in tInfo.GetFiles())
            {
                CreateFileCopyTask(fileInfo.FullName, parentDir, connection);
            }
        }

        private void CreateFileCopyTask(string file, string parentDir, NetConnection connection)
        {
            try
            {
                var tFile = new FileInfo(file);
                var sc = new StreamingServer(Network, connection, file, parentDir + tFile.Name, _number++);
                _fileQueue.Enqueue(sc);
            }
            catch (Exception)
            {
                // todo 失败处理
            }

        }

        public void NotifyNewFileCanCopy(List<string> dirList, List<string> fileList)
        {
            if (dirList.Count == 0 && fileList.Count == 0)
            {
                return;
            }
            if (!Network.IsConnected)
            {
                return;
            }

            var message = new NotifyNewFileCanCopyMessge();
            message.Init(dirList,fileList);
            Network.SendMessage(message, NetDeliveryMethod.ReliableOrdered, Channel);
        }

        public void NotifyNewTextCanCopy(string getText)
        {
            var tMessage = new NotifyNewTextCanPasteMessage {Text = getText};
            Network.SendMessage(tMessage);
        }
    }
}